package socket2;

import com.sun.prism.shader.AlphaOne_LinearGradient_Loader;
import day01.C;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class Server {
    private ServerSocket serverSocket;
    private Map<String,PrintWriter> allOut = new HashMap<>();

    public Server(){
        try {
            System.out.println("正在启动服务器。。。");
            serverSocket = new ServerSocket(8080);
            System.out.println("服务器启动完毕。");
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    public void start(){
        System.out.println("等待客户端连接");
        while(true){
            try {
                Socket socket = serverSocket.accept();
                System.out.println("一个客户端连接了");
                ClientHandler handler = new ClientHandler(socket);
                Thread t = new Thread(handler);
                t.start();


            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public class ClientHandler implements Runnable{
        private Socket socket;
        private String host;
        private String nickname;
        public ClientHandler(Socket socket){
            this.socket=socket;
            host=socket.getInetAddress().getHostAddress();//获取客户端IP地址
        }
        public void run(){
            PrintWriter pw =null;
            try {
                InputStream inputStream = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
                BufferedReader br = new BufferedReader(isr);
                nickname = br.readLine();

                OutputStream os = socket.getOutputStream();
                OutputStreamWriter osw = new OutputStreamWriter(os,StandardCharsets.UTF_8);
                BufferedWriter bw = new BufferedWriter(osw);
                pw = new PrintWriter(bw,true);
                synchronized (allOut){
                    allOut.put(nickname,pw);
                }
                broadcast(nickname+"["+host+"]已上线，当前在线人数"+allOut.size());


                String message;

                while((message=br.readLine())!=null){
                    if(message.startsWith("@")){
                        sendMessageToSomeone(message);
                    }else{
                        broadcast(nickname+"["+host+"]:"+message);
                    }

                }

            } catch (IOException e) {

            } finally {
                synchronized(allOut){
                    allOut.remove(nickname);
                    //System.out.println(allOut);
                }
                broadcast(nickname+"["+host+"]已下线，当前在线人数"+allOut.size());

                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        private void sendMessageToSomeone(String message){

            if(message.matches("@.+:.+")){
                String toNickname = message.substring(1,message.indexOf(":"));
                String toMessage =message.substring(message.indexOf(":")+1);
                if(allOut.containsKey(toNickname)){
                    PrintWriter pwToSomeone = allOut.get(toNickname);
                    pwToSomeone.println("来自"+nickname+"的私信:"+toMessage);
                }else{
                    PrintWriter pwToMe = allOut.get(nickname);
                    pwToMe.println("没有这个人");
                }
            }else{
                PrintWriter pwToMe = allOut.get(nickname);
                pwToMe.println("私聊格式不正确");
            }
        }
    }
    public void broadcast(String str){
        System.out.println(str);
        synchronized(allOut){
            for(PrintWriter pw:allOut.values()){
                pw.println(str);
            }
        }

    }

    public static void main(String[] args) {
        Server server = new Server();
        server.start();
    }
}
